import {AppRequestInterface, InternalRequestConfig,} from "./app-request-type.ts";
import AppRequestUtil from "./app-request-util.ts";

/**
 * 请求成功拦截器。不能使用箭头函数，否则无this
 * @param requestConfig
 */
const handleRequestFulfilled = function handleRequestFulfilled(
    this: AppRequestInterface,
    requestConfig: InternalRequestConfig
) {
  // log.debug("requestConfig：{}", requestConfig);

  // loading
  if (
      typeof requestConfig.showLoading === "function"
          ? requestConfig.showLoading()
          : requestConfig.showLoading
  ) {
    requestConfig.showLoadingFunction();
  }

  // header
  requestConfig.beforeAddRequestHeaders.bind(this)(requestConfig);
  requestConfig.addRequestHeaders(requestConfig.headers);
  requestConfig.afterAddRequestHeaders(requestConfig);

  // mock
  if (!AppRequestUtil.isMocked(requestConfig.url, this.mockConfig)) {
    return requestConfig;
  }

  const mockTarget = AppRequestUtil.mockTarget(
      requestConfig.url,
      this.mockConfig
  );
  requestConfig.url = mockTarget + requestConfig.url;
  return requestConfig;
};

export default handleRequestFulfilled;
